package com.wei.shopping.controller;

import com.wei.shopping.entrty.PageResult;
import com.wei.shopping.entrty.QueryPageBean;
import com.wei.shopping.entrty.Result;
import com.wei.shopping.pojo.*;
import com.wei.shopping.service.*;
import com.wei.shopping.utils.KeyUtil;
import com.wei.shopping.utils.QiniuUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/commodity")
public class CommController {
    @Resource
    private CommService commService;
    @Resource
    private LoginService loginService;
    @Resource
    private UserService userService;
    @Resource
    private CommentService commentService;
    @Resource
    private NoticesService noticesService;
    @Resource
    private CollectService collectService;
    @Resource
    private SoldService soldService;
    @RequestMapping("/findall")
    @ResponseBody
    public PageResult findall(@RequestBody QueryPageBean queryPageBean, @RequestParam("commstatus") Integer commstatus ){
        try{
            PageResult page = commService.findall(queryPageBean, commstatus);
            return page;
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 设置商品违规
     * @param commdity
     * @return
     */
    @RequestMapping("/violation")
    @ResponseBody
    public Result violation(@RequestBody Commodity commdity){
        try{
            commService.violation(commdity);
            return new Result(true,"设置违规成功");
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,"设置违规失败");
        }
    }

    /**
     * 审核通过
     * @return
     */
    @RequestMapping("/pass")
    @ResponseBody
    public Result psss(@RequestBody Commodity commodity){
        try{
            commService.pass(commodity);
            return new Result(true,"审核通过成功");
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,"审核通过失败");
        }
    }

    /**
     * 商品详情
     * @param commid
     * @param modelMap
     * @param session
     * @return
     */
    @RequestMapping("/detail/{commid}")
    public String detail(@PathVariable("commid") String commid, ModelMap modelMap, HttpSession session){
        System.out.println("commid:"+commid);
        //获取userid
        String userid = (String)session.getAttribute("userid");
        //通过commid进行查询
        Commodity commo = commService.findById(commid);
        System.out.println("comm:"+commo);
        int i = 0;
        if(commo.getCommstatus().equals(1)){
            //判断商品是否正常
            i = 1;
        }else if (!StringUtils.isEmpty(userid)){//如果用户已登录
            Login login = new Login();
            login.setUserid(userid);
            Login log = loginService.findByAll(login);
            //查找售出商品记录，判断是否是本人购买的商品
            Sold sold = soldService.findByCommid(commid);
            /**商品为违规状态时：本人和管理员可查看*/
            if (commo.getCommstatus().equals(0) && (commo.getUserid().equals(userid) || (log.getRoleid().equals(2)))){
                i=1;
                /**商品为待审核状态时：本人和管理员可查看*/
            }else if (commo.getCommstatus().equals(3) && (commo.getUserid().equals(userid) || (log.getRoleid().equals(2)))){
                i=1;
                /**商品为已售出状态时：本人,卖家和管理员可查看*/
            }else if (commo.getCommstatus().equals(4) && (commo.getUserid().equals(userid) || (log.getRoleid().equals(2)) || userid.equals(sold.getUserid()))){
                i=1;
                /**商品为已删除时，本人和管理员可查看*/
            }else if (commo.getCommstatus().equals(2) && (commo.getUserid().equals(userid) || (log.getRoleid().equals(2)) || userid.equals(sold.getUserid()))){
                i=1;
            }
        }
        if(i==1){
            //commodity.setOtherimg(commimagesService.LookGoodImages(commid));
            /**商品浏览量+1*/
            commService.addLiulan(commid);
            modelMap.put("userinfo",userService.findById(commo.getUserid()));
            //获取商品详情图片
            List<String> detailpic = commService.detailpic(commid);
            modelMap.put("detailpic",detailpic);
            modelMap.put("gddetail",commo);
            //当前用户的id
            modelMap.put("nowuserid",userid);
            //如果没有用户登录
            if (StringUtils.isEmpty(userid)){
                modelMap.put("collectstatus",2);
            }else {
                //登陆了，查询此商品是否被收藏
                Collect collect = collectService.findByCommidAndUserid(commid,userid);
                if(collect!=null){
                        modelMap.put("collectstatus",1);
                }else {
                    modelMap.put("collectstatus",2);
                }
            }
            return "/commodity/commdetail";
        }else{
            return "/error/404";
        }
    }
    @RequestMapping("/findCommentByCommId")
    @ResponseBody
    public PageResult findCommentByCommId(@RequestParam("commid") String commid,@RequestBody QueryPageBean queryPageBean){
        //获取评论信息
        PageResult pageResult = commentService.findByCommId(commid,queryPageBean);
        return pageResult;
    }
    /**
     * 上传图片
     * @param image
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("image") MultipartFile image){
        //获取文件的原始文件明
        String originalFilename = image.getOriginalFilename();
        //获取文件的后缀名
        int last = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(last);
        //获取随机的文件名称
        String filename = UUID.randomUUID().toString()+ substring;
        //上传文件到服务器
        try{
            QiniuUtils.upload2Qinui(image.getBytes(), filename);
            Result result = new Result(true,"图片上传成功");
            result.setData(filename);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, "图片上传失败");
        }
    }
    /**
     * 上传其他图片
     */
    @RequestMapping("/imagelist")
    @ResponseBody
    public Result imagelist(@RequestParam(value = "file", required = false) MultipartFile file) {
        //获取文件的原始文件明
        String originalFilename = file.getOriginalFilename();
        //获取文件的后缀名
        int last = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(last);
        //获取随机的文件名称
        String filename = UUID.randomUUID().toString()+ substring;
        //上传文件到服务器
        try{
            QiniuUtils.upload2Qinui(file.getBytes(), filename);
            System.out.println("filename : "+ filename);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, "图片上传失败");
        }
        return new Result(true,"图片上传成功",filename);
    }

    /**
     * 上传商品
     * @param commodity
     * @return
     */
    @RequestMapping("/submit")
    @ResponseBody
    public Result submit(@RequestBody Commodity commodity, HttpSession session){
        //获取userid
        String userid =(String) session.getAttribute("userid");
        //获取学生学校
        String school = (String) session.getAttribute("school");
        //获取随机commid
        String commid = KeyUtil.genUniqueKey();
        commodity.setUserid(userid);
        commodity.setSchool(school);
        commodity.setCommid(commid);
        try{
            //插入数据库
            commService.addComm(commodity);
            //详情图片，插入数据库
            String imageList = commodity.getImageList();
            commService.addImage(imageList,commid);
            return new Result(true,"上架商品成功");
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,"上架商品失败");
        }

    }

    /**
     * 删除上传的图片
     * @param file
     * @return
     */
    @RequestMapping("/removeImage")
    @ResponseBody
    public Result removeImage(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        try{
            QiniuUtils.deleteFileFromQiniu(originalFilename);
            return new Result(true,"删除成功");
        }catch(Exception e){
            return new Result(false,"删除失败");
        }
    }

    /**
     * 根据userid查找全部商品
     * @param queryPageBean
     * @param commstatus
     * @return
     */
    @RequestMapping("/findallbyuserid")
    @ResponseBody
    public PageResult findallbyuserid(@RequestBody QueryPageBean queryPageBean,
                                      @RequestParam("commstatus") Integer commstatus,
                                      HttpSession session){
        try{
            String userid = (String)session.getAttribute("userid");
            PageResult allByUserId = commService.findAllByUserId(queryPageBean, commstatus, userid);
            return allByUserId;
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 设置商品已售出
     * @param commid
     * @return
     */
    @RequestMapping("/solded")
    @ResponseBody
    public Result solded(@RequestParam("commid") String commid,HttpSession session){
        try{
            String userid = (String) session.getAttribute("userid");
            commService.solded(commid,userid);
            return new Result(true,"商品设置售出成功");
        }catch(Exception e){
            return new Result(false,"商品设置失败");
        }
    }

    /**
     * 删除商品
     * @param commid
     * @return
     */
    @RequestMapping("/deletecomm")
    @ResponseBody
    public Result deletecomm(@RequestParam("commid") String commid){
        try{
            commService.deletecomm(commid);
            return new Result(true,"删除商品成功");
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,"商品删除失败");
        }
    }

    /**
     * 通过商品id查找商品
     * @param commid
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCommid")
    public Result findByCommid(@RequestParam("commid") String commid){
        try{
            Map map = commService.findByCommid(commid);
            return new Result(true,"查找数据成功",map);
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,"查找数据失败");
        }
    }

    /**
     * 修改商品信息
     * @param commodity
     * @return
     */
    @ResponseBody
    @RequestMapping("/updatecomm")
    public Result updatecomm(@RequestBody Commodity commodity){
        try{
            System.out.println("commodity: "+ commodity);
            commService.updatecomm(commodity);
            return new Result(true,"修改商品成功");
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,"修改商品信息失败");
        }
    }

    /**
     * 获取8个热门商品
     * @return
     */
    @RequestMapping("/hotcomm")
    @ResponseBody
    public Result hotcomm(){
        try{
            Map map = commService.hotcomm();
            return new Result(true,"查找成功",map);
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,"查找失败");
        }
    }

    /**
     * 上传评论
     * @return
     */
    @RequestMapping("/addcomment")
    @ResponseBody
    public Result addcomment(@RequestBody Comment comment,HttpSession session){
        UserInfo user = userService.findById((String) session.getAttribute("userid"));
        Commodity commodity = commService.findById(comment.getCommid());
        comment.setCid(KeyUtil.genUniqueKey());
        comment.setCuserid(user.getUserid());
        comment.setCuserimage(user.getUimage());
        comment.setCusername(user.getUsername());
        try{
            //添加评论
            commentService.addComment(comment);
            //添加通知
            Notices notices = new Notices();
            notices.setId(KeyUtil.genUniqueKey());
            notices.setUserid(user.getUserid());
            notices.setTpname("商品评论");
            notices.setWhys("你的商品"+ commodity.getCommname() + "被评论了，快去看看吧");
            //添加通知
            noticesService.addnotices(notices);
            return new Result(true,"评论成功");
        }catch(Exception e){
            return new Result(false,"评论失败");
        }
    }

    /**
     * 通过类别，查找条件，排列循序分页查询
     * @param queryPageBean
     * @param category
     * @param paixu
     * @return
     */
    @ResponseBody
    @RequestMapping("/findAllByAll")
    public PageResult findAllByAll(@RequestBody QueryPageBean queryPageBean,
                                   @RequestParam("category") String category,
                                   @RequestParam("paixu") String paixu,
                                   @RequestParam("minprice") Integer minprice,
                                   @RequestParam("maxprice") Integer maxprice){
        //判断最低价和最高价是否合法
        if(minprice > maxprice){
            //最低价大于最高价,调转
            Integer midder = minprice;
            minprice = maxprice;
            maxprice = midder;
        }
        PageResult allByAll = commService.findAllByAll(queryPageBean, category, paixu,minprice,maxprice);
        return allByAll;
    }

    /**
     * 添加网站反馈
     * @return
     */
    @RequestMapping("/addfeedback")
    @ResponseBody
    public Result addfeedback(@RequestBody Feedback feedback,HttpSession session){
        //获取用户id
        String userid = (String)session.getAttribute("userid");
        feedback.setUserid(userid);
        feedback.setId(KeyUtil.genUniqueKey());
        System.out.println(feedback);
        try{
            commService.addfeedback(feedback);
            return new Result(true,"添加反馈成功");
        }catch(Exception e){
            return new Result(false,"添加反馈失败");
        }
    }
    /**
     * 商品搜索
     */
    @RequestMapping("/lookfor")
    public String lookfor(@RequestParam("inputString") String inputString,ModelMap modelMap){
        modelMap.put("inputString",inputString);
        return "/commodity/commolist";
    }

    /**
     * 商品收藏和取消收藏
     * @param commid
     * @param flag
     * @param session
     * @return
     */
    @RequestMapping("/collect")
    @ResponseBody
    public Result collect(@RequestParam("commid")String commid,@RequestParam("flag") Integer flag,HttpSession session){
        String userid = (String)session.getAttribute("userid");
        if(flag == 0){
            //收藏商品
            collectService.collect(commid,userid);
            return new Result(true,"收藏成功");
        }else if(flag == 1){
            //取消收藏
            collectService.cancelcollect(commid,userid);
            return new Result(true,"取消收藏成功");
        }else{
            return new Result(false,"网络错误");
        }
    }

    @RequestMapping("/purchase")
    @ResponseBody
    public Result purchase(@RequestBody Commodity commodity,HttpSession session){
        String userid = (String)session.getAttribute("userid");
        //设置销售记录
        Sold sold = new Sold();
        sold.setCommid(commodity.getCommid());
        sold.setId(KeyUtil.genUniqueKey());
        sold.setUserid(userid);
        sold.setCommdesc(commodity.getCommdesc());
        sold.setCommname(commodity.getCommname());
        sold.setSoldmoney(commodity.getThinkmoney());
        sold.setCategory(commodity.getCategory());
        sold.setCommuserid(commodity.getUserid());
        //设置通知信息
        Notices notices = new Notices();
        notices.setId(KeyUtil.genUniqueKey());
        notices.setTpname("商品售出");
        notices.setWhys("你的商品："+ commodity.getCommname()+",已售出");
        notices.setUserid(commodity.getUserid());
        //设置商品信息
        commodity.setCommstatus(4);
        try{
            //添加销售记录
            soldService.addSold(sold);
            //通知用户商品售出
            noticesService.addnotices(notices);
            //修改商品信息为已售出
            commService.updatestatus(4,commodity.getCommid());
            return new Result(true,"购买成功");
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,"网络错误");
        }
    }
}
